package JavaSE.SerializationWithStatic;

import java.io.*;

/**
 *  测试
 *      在被序列化流的对象里有 static 变量时
 *      从生成的 .dat 文件中读取对象信息
 *      结果为：Student{id=9527, name='张三', teacher=Teacher{name='李四', course='null'}}
 *
 *      注释掉创建对象的语句和输出到文件的语句后
 *      直接从生成的 .dat 文件中读取对象数据信息
 *      发现结果变成了：Student{id=0, name='wno', teacher=Teacher{name='李四', course='null'}}
 *
 *  结论
 *      可以看出 static 修饰的变量本身是不会被序列化的
 *      我们读取的值是当前jvm中的方法区对应此变量的值
 *      所以最后输出的值为我们对 static 变量后赋的值
 */
public class SerializationWithStatic {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Student student = new Student(9527, "张三", new Teacher("李四", "语文"));
        //System.out.println(student.toString());
        //ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("src\\JavaSE.SerializationWithStatic\\a.dat"));
        //oos.writeObject(student);
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("src\\JavaSE.SerializationWithStatic\\a.dat"));
        Object data = ois.readObject();
        Student.id = 29;
        System.out.println("读取对象文件的内容：");
        System.out.println(data.toString());
    }
}

//Serialization
class Student implements Serializable {
    static int id;
    static String name = "wno";
    private Teacher teacher;
    String hobby;

    Student(int id, String name, Teacher teacher) {
        this.id = id;
        this.name = name;
        this.teacher = teacher;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", teacher=" + teacher +
                '}';
    }
}

class Teacher implements Serializable {
    static final long serialVersionUID = 4L;
    private String name;
    private transient String course = "数学";

    Teacher(String name, String course) {
        this.name = name;
        this.course = course;
    }

    @Override
    public String toString() {
        return "Teacher{" +
                "name='" + name + '\'' +
                ", course='" + course + '\'' +
                '}';
    }
}
